/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.rs.service.impl;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import com.xy.biz.rs.domain.converter.MaterialConverter;
import com.xy.biz.rs.domain.req.SaveMaterialRequest;
import com.xy.lang.domain.Result;
import com.xy.tool.context.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xy.biz.rs.domain.bo.MaterialBO;
import com.xy.biz.rs.domain.query.MaterialQuery;
import com.xy.biz.rs.service.MaterialService;
import com.xy.biz.rs.manager.MaterialManager;

/**
 *
 *
 * @author yzh
 * @date 2021-4-14
 */
@Service
public class MaterialServiceImpl implements MaterialService {

	@Autowired
	private MaterialManager materialManager;

	@Override
	public Result<?> saveMaterial(SaveMaterialRequest request) {
		MaterialBO materialBO = MaterialConverter.toBO(request);
		buildMaterial(materialBO);
		int affectedRows = materialManager.saveMaterial(materialBO);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	private void buildMaterial(MaterialBO materialBO){
		LocalDateTime now = LocalDateTime.now();
		materialBO.setDeleteFlag(false);
		materialBO.setTenantId(UserContextHolder.getTenantId());
		materialBO.setCreateTime(now);
		materialBO.setUpdateTime(now);
	}

	@Override
	public Result<?> saveAllMaterial(Collection<MaterialBO> collection) {
		int affectedRows = materialManager.saveAllMaterial(collection);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	@Override
	public Result<?> updateMaterial(SaveMaterialRequest request) {
		int affectedRows = materialManager.updateMaterial(MaterialConverter.toBO(request));
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	@Override
	public Result<?> deleteMaterial(Long materialId) {
		int affectedRows = materialManager.deleteMaterial(materialId);
		if (affectedRows > 0) {
			return Result.success();
		}
		return Result.ofErrorRowsAffected();
	}

	@Override
	public MaterialBO getMaterial(Long materialId) {
		return materialManager.getMaterial(materialId);
	}

	@Override
	public List<MaterialBO> listMaterialById(Collection<Long> collection) {
		return materialManager.listMaterialById(collection);
	}

	@Override
	public List<MaterialBO> listMaterial(MaterialQuery query) {
		return materialManager.listMaterial(query);
	}

	@Override
	public int countMaterial(MaterialQuery query) {
		return materialManager.countMaterial(query);
	}

}
